public class Solution129 {
    int res = 0;

    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
        dfs(root, 0);
        return res;
    }

    private void dfs(TreeNode root, int sum) {
        sum += root.val;
        if (root.left == null && root.right == null) {
            res += sum;
        }
        if (root.left != null) {
            dfs(root.left, sum * 10);
        }
        if (root.right != null) {
            dfs(root.right, sum * 10);
        }
    }
}
